package org.example.servlet;

import org.example.dao.AddressDAO;
import org.example.dao.AddressDAOImpl;
import org.example.model.Address;
import org.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.stream.Collectors;

@WebServlet("/address/*")
public class AddressServlet extends HttpServlet {
    private AddressDAO addressDAO = new AddressDAOImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        
        if (pathInfo == null || pathInfo.equals("/")) {
            // 获取用户的所有地址
            HttpSession session = request.getSession();
            Integer userId = (Integer) session.getAttribute("userId");
            
            if (userId != null) {
                List<Address> addresses = addressDAO.findByUserId(userId);
                System.out.println("Found " + addresses.size() + " addresses for user " + userId);
                request.setAttribute("addresses", addresses);
                request.getRequestDispatcher("/address.jsp").forward(request, response);
            } else {
                response.sendRedirect("login.jsp");
            }
        } else if ("/get".equals(pathInfo)) {
            getAddress(request, response);
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        
        switch (pathInfo) {
            case "/save":
                saveAddress(request, response);
                break;
            case "/delete":
                deleteAddress(request, response);
                break;
            case "/setDefault":
                setDefaultAddress(request, response);
                break;
        }
    }
    
    private void getAddress(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        JSONObject result = new JSONObject();
        
        try {
            Integer addressId = Integer.parseInt(request.getParameter("addressId"));
            Address address = addressDAO.findById(addressId);
            
            if (address != null) {
                result.put("success", true);
                result.put("data", new JSONObject()
                    .put("addressId", address.getAddressId())
                    .put("receiver", address.getReceiver())
                    .put("phone", address.getPhone())
                    .put("province", address.getProvince())
                    .put("city", address.getCity())
                    .put("district", address.getDistrict())
                    .put("detailAddress", address.getDetailAddress())
                    .put("isDefault", address.getIsDefault())
                );
            } else {
                result.put("success", false);
                result.put("message", "地址不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        
        out.print(result.toString());
    }
    
    private void saveAddress(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        JSONObject result = new JSONObject();
        
        try {
            // 读取请求体
            String body = request.getReader().lines().collect(Collectors.joining());
            JSONObject addressData = new JSONObject(body);
            
            // 获取用户ID
            HttpSession session = request.getSession();
            Integer userId = (Integer) session.getAttribute("userId");
            
            if (userId == null) {
                result.put("success", false);
                result.put("message", "请先登录");
                out.print(result.toString());
                return;
            }
            
            // 创建地址对象
            Address address = new Address();
            address.setUserId(userId);
            address.setReceiver(addressData.getString("receiver"));
            address.setPhone(addressData.getString("phone"));
            address.setProvince(addressData.getString("province"));
            address.setCity(addressData.getString("city"));
            address.setDistrict(addressData.getString("district"));
            address.setDetailAddress(addressData.getString("detailAddress"));
            address.setIsDefault(addressData.optBoolean("isDefault", false));
            
            // 如果有addressId，则是更新操作
            String addressId = addressData.optString("addressId", null);
            boolean success;
            if (addressId != null && !addressId.isEmpty()) {
                address.setAddressId(Integer.parseInt(addressId));
                success = addressDAO.update(address);
            } else {
                success = addressDAO.save(address);
            }
            
            result.put("success", success);
            if (!success) {
                result.put("message", "保存失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        
        out.print(result.toString());
    }
    
    private void deleteAddress(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        JSONObject result = new JSONObject();
        
        try {
            Integer addressId = Integer.parseInt(request.getParameter("addressId"));
            boolean success = addressDAO.delete(addressId);
            
            result.put("success", success);
            if (!success) {
                result.put("message", "删除失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        
        out.print(result.toString());
    }
    
    private void setDefaultAddress(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        JSONObject result = new JSONObject();
        
        try {
            HttpSession session = request.getSession();
            Integer userId = (Integer) session.getAttribute("userId");
            Integer addressId = Integer.parseInt(request.getParameter("addressId"));
            
            if (userId == null) {
                result.put("success", false);
                result.put("message", "请先登录");
                out.print(result.toString());
                return;
            }
            
            boolean success = addressDAO.setDefault(userId, addressId);
            result.put("success", success);
            if (!success) {
                result.put("message", "设置默认地址失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        
        out.print(result.toString());
    }
} 